<?php

Class AdminModel
{
    public function __construct()
    {
        $this->db = Yaf_Registry::get('_db');
    }

    public function checklogin($username, $password)
    {
        $sql = "select * from t_admin 
                    where username='" . $username . "' and status = 1";
        $result = $this->db->get_row($sql);

        if ($result){
            if ($result->password != $password) {
                return false;
            }else{
                return array($result->id, $result->roleid);
            }
        }else{
            return false;
        }
    }

    public function find($uid)
    {
        $sql = "select * from t_admin where id = $uid";
        $result = $this->db->get_row($sql);
        if ($result){
            return $result;
        }else {
            return NULL;
        }
    }

    public function selectAll($start = 0, $length = 20, $searchkey = '')
    {
        $wheresql = ' where 1=1 ';
        if (isset($searchkey) && !empty($searchkey)){
            $wheresql .= " and username like '%$searchkey%'";
        }
        
        // 获取总数
        $countsql = "select count(id) from t_admin " . $wheresql;
        $total = $this->db->get_var($countsql);
        
        // 获取分页数据
        $sql = "select a.id, a.username, a.email, b.name as rolename, a.createtime, a.status 
                    from t_admin as a
                    left join t_role as b on a.roleid = b.id 
                    " . $wheresql . " order by id desc limit $start, $length";
        $result = $this->db->get_results($sql);

        return array($total, $result);
    }

    public function insert($info)
    {
        $username = $info['username'];
        $email = $info['email'];
        $password = $info['password'];
        $role = $info['role'];
        $createtime = date('Y-m-d H:i:s');
        $status = 1;
        $sql = "insert into t_admin(username, email, password, roleid, createtime, status)
                    values('$username', '$email', '$password', $role, '$createtime', $status)";
                    
        $result = $this->db->query($sql);
        return $result;
    }
    
    //检查是否同名
    public function checkusername($username='')
    {
        $sql = "select id from t_admin where username = '$username'";
        $result = $this->db->get_var($sql);
        if ($result){
            return true;
        }else{
            return false;
        }
    }

    public function updatepassword($uid, $newpwd)
    {
        $sql = "update t_admin set password = '$newpwd' where id = $uid";
        $result = $this->db->query($sql);
        return $result;
    }

    public function update($info)
    {
        $email = $info['email'];
        $status = $info['status'];
        $uid = $info['id'];
        $roleid = $info['roleid'];
        $sql = "update t_admin set status = $status, email = '$email', roleid = $roleid where id = $uid";
        $result = $this->db->query($sql);
        return $result;
    }
}